import psutil
import os
import signal
import platform


def kill_process_by_pid(pid):
    system = platform.system()
    try:
        if system == 'Windows':
            import subprocess
            subprocess.run(['taskkill', '/F', '/PID', str(pid)], check=True)
        elif system == 'Linux' or system == 'Darwin':
            os.kill(pid, signal.SIGTERM)
        else:
            print(f"不支持的操作系统: {system}")
            return False
        print(f"进程 {pid} 已成功关闭。")
        return True
    except OSError as e:
        print(f"关闭进程 {pid} 时出错: {e}")
        return False
    except subprocess.CalledProcessError as e:
        print(f"关闭进程 {pid} 时出错: {e}")
        return False
def get_process_count(name):
    count = 0
    for proc in psutil.process_iter(['name']):
        try:
            if proc.info['name'] == name:
                count += 1
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return count
def get_process_cpu_memory(name,keys,interval=0.01):
    rst={}

    for proc in psutil.process_iter(['name','cmdline']):
        try:
            if proc.info['name'] == name:
                cmd = " ".join(proc.info['cmdline'])
                ispass=True
                for i in keys:
                    if i not in cmd:
                        ispass=False
                if ispass:
                    cpu_percent = proc.cpu_percent(interval=interval)
                    mem_percent = proc.memory_percent()
                    # memory_info = proc.memory_info()
                    # memory_info_ex = proc.memory_info_ex()
                    # memory_full_info = proc.memory_full_info()
                    rst[proc.pid]=(cpu_percent,mem_percent)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return rst
def get_process_count_cpu_memory(name,keys,interval=0.01):
    rst={}
    count = 0
    for proc in psutil.process_iter(['name','cmdline']):
        try:
            if proc.info['name'] == name:
                cmd = " ".join(proc.info['cmdline'])
                ispass=True
                for i in keys:
                    if i not in cmd:
                        ispass=False
                if ispass:
                    count=count+1
                    cpu_percent = proc.cpu_percent(interval=interval)
                    mem_percent = proc.memory_percent()
                    # memory_info = proc.memory_info()
                    # memory_info_ex = proc.memory_info_ex()
                    # memory_full_info = proc.memory_full_info()
                    rst[proc.pid]=(cpu_percent,mem_percent)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return count,rst

if __name__=="__main__":
    r=get_process_cpu_memory("python.exe",["--multiprocessing-fork"])
    for p in r.keys():
        kill_process_by_pid(p)